package com.ftg.learn.chapter02.java.pool;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学习容器 -
 *
 * animals工厂可以吗?
 * containers  提交把要用到的存储起来，想用的时候，就一定有，不用每次都去创建  IOC
 * @author kangjx
 * @version 1.0
 * @date 2023/12/25 上午8:27
 */
public class Third {

    public Third(){
        this.open();
    }

    Map<String,Object> containers = new HashMap<>(4);
    public static  void main(String[] args) {
        Third f = new Third();

        Dog dog = (Dog)f.containers.get("dog");
        System.out.println(dog.getName());
        Object dog1 = f.containers.get("cat");

    }

    /**
     * 打开货源 进货.xml
     */
    public void open(){
        //货源 进货 .xml
        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read("/home/kangjx/userpanel/workspace/java/learnjava2309/learnjava2309/src/main/resources/dayifactory.xml");
            Element dayi = read.getRootElement();

            List<Element> animals = dayi.elements();

            for (Element animal : animals) {
                Attribute key = animal.attribute("key");
                Attribute value = animal.attribute("value");

                Element name = animal.element("name");
                String nameVal = name.getText();

                Element type = animal.element("type");
                String typeVal = type.getText();

                Element color = animal.element("color");
                String colorVal = color.getText();
                try {
                    Class clazz = (Class) Class.forName(value.getValue());
                    Object obj = this.animalsFactory(clazz,nameVal,typeVal,colorVal);
                    containers.put(key.getValue(),obj);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }

        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }

    }


    /**
     * 第四种
     */
    public <T> T createInstance3(Class<T> clazz) {
        try {
            return clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 第一种
     * @param clazz
     * @param name
     * @param type
     * @param color
     * @return
     * @param <T>
     */
    public <T extends Animals> T animalsFactory(Class<T> clazz,String name,String type,String color) {
        T animals =  createInstance3(clazz);
        animals.setName(name);
        animals.setType(type);
        animals.setColor(color);
        return animals;
    }

}
